package pailaidai.hc.com.mysvgdemo.view;

import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Rect;
import android.support.annotation.Nullable;
import android.util.AttributeSet;
import android.view.View;

/**
 * Created by Administrator on 2018/4/4.
 */

public class FirstView extends View {
    private static final String TEXT = "如蜗牛般一样进步";
    private Paint paint;

    public FirstView(Context context) {
        super(context);
    }

    public FirstView(Context context, @Nullable AttributeSet attrs) {
        super(context, attrs);
        paint = new Paint(Paint.ANTI_ALIAS_FLAG);
        paint.setTextSize(100);
        paint.setColor(Color.RED);
    }

    public FirstView(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
    }

    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);
        //将文字放在正中间
        Rect textRect = getTextRect();
        int viewWidth = getMeasuredWidth();
        int viewHeight = getMeasuredHeight();
        Paint.FontMetrics fontMetrics = paint.getFontMetrics();
        int x = (viewWidth - textRect.width()) / 2;
        int y = (int) (viewHeight / 2 + (fontMetrics.descent - fontMetrics.ascent) / 2 - fontMetrics.descent);
        canvas.drawText(TEXT, x, y, paint);
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        Rect rect = getTextRect();
        int textWidth = rect.width();
        int textHeight = rect.height();
        int width = measureWidth(widthMeasureSpec, textWidth);
        int height = measureHeight(heightMeasureSpec, textHeight);
        setMeasuredDimension(width, height);
    }

    private int measureHeight(int heightMeasureSpec, int textHeight) {
        


        return 0;
    }

    private int measureWidth(int widthMeasureSpec, int textWidth) {
        int mode=MeasureSpec.getMode(widthMeasureSpec);
        int size=MeasureSpec.getSize(widthMeasureSpec);
        int width=0;
        if(mode==MeasureSpec.EXACTLY){
            width=size;
        }else if(mode==MeasureSpec.AT_MOST){
            width=textWidth;
        }
        return width;
    }

    /**获取文字所占的尺寸
     * */
    public Rect getTextRect() {
       //根据Paint设置的绘制参数计算文字所占的宽度
        Rect rect=new Rect();
        //文字多占的区域大小保存在rect中
        paint.getTextBounds(TEXT,0, TEXT.length(),rect);
        return rect;
    }
}
